package org.magnerfuller.imtoolkit.server.connection.handler;

import java.util.Map;
import java.util.Vector;

import org.magnerfuller.imtoolkit.server.connection.event.ConnectionEvent;
import org.magnerfuller.imtoolkit.server.connection.event.listener.ConnectionListener;
import org.magnerfuller.imtoolkit.server.naming.NamedModule;
import org.magnerfuller.imtoolkit.server.service.ServiceDescription;
import org.magnerfuller.imtoolkit.server.session.medium.SessionDescription;

/**
 * 
 * Abstract Class ConnectionHandler
 *
 * Objects of this class handle connections of some kind, and should
 * notify listeners of the connections made, so that they can be managed.
 * 
 * One must create a class extending ConnectionHandler in order to
 * implement the support of a new communication protocol.
 * 
 */
public abstract class ConnectionHandler extends Thread implements NamedModule {
  /** listeners -- This is the vector of listeners that are notified of events. */
  protected Vector<ConnectionListener> listeners;

  /** serviceDesc -- This describes what services are generated from connections. */
  protected ServiceDescription serviceDesc = null;
  
  /**
   * Constructor
   */
  public ConnectionHandler() {
    super();
    listeners = new Vector<ConnectionListener>();
  }//ConnectionHandler
  
  /**
   * Initialize from a Map of parameters.
   * 
   * @param params the string parameter table.
   * @throws Exception -- Throw whatever you need to throw... management code
   *                      should handle it.
   */
  public abstract void initialize(Map<String, String> params) throws Exception;

  /**
   * Add a Connection Listener.
   *
   * @param l The Connection Listener
   */
  public void addConnectionListener(ConnectionListener l) {
    listeners.addElement(l);
  }//addConnectionListener

  /**
   * Remove a Connection Listener.
   *
   * @param l The Connection Listener
   * @return true if the element was present, false if not.
   */
  public boolean removeConnectionListener(ConnectionListener l) {
    return listeners.removeElement(l);
  }//removeConnectionListener

  /**
   * Fire a Connection Event to all listeners.
   *
   * @param e The Connection Event
   */
  public void fireConnectionEvent(ConnectionEvent e) {
    for(ConnectionListener l : listeners) {
      l.connectionOccurred(e);
    }
  }//fireConnectionEvent

  /**
   * Implement this method as the implementation of Thread class.
   */
  public abstract void run();
  
  /**
   * Get the service description.
   * 
   * @return the service description
   */
  public ServiceDescription getServiceDescription() {
    return serviceDesc;
  }//getServiceDescription
  
  /**
   * Set the service description.
   * 
   * @param desc the service description
   */
  public void setServiceDescription(ServiceDescription desc) {
    this.serviceDesc = desc;
  }//setServiceDescription
  
}//ConnectionHandler
